// 默认配置
const DEFAULT_CONFIG = {
  baseURL: "http://localhost:8080",
  timeout: 10000,
  loading: true,
  loadingText: "加载中...",
  needAuth: true, // 是否需要携带token
  header: {
    "Content-Type": "application/json",
    "X-Requested-With": "XMLHttpRequest",
  },
};

class HttpRequest {
  constructor(config = {}) {
    this.config = { ...DEFAULT_CONFIG, ...config };
    this.interceptors = { request: [], response: [] };
  }

  // 添加请求拦截器
  addRequestInterceptor(interceptor) {
    this.interceptors.request.push(interceptor);
    return this;
  }

  // 添加响应拦截器
  addResponseInterceptor(interceptor) {
    this.interceptors.response.push(interceptor);
    return this;
  }
  // 新增统一响应处理方法
  handleResponse(res, resolve, reject) {
    // 判断是否是错误响应（来自fail回调）
    if (res.statusCode === undefined && res.errMsg) {
      // 处理网络错误等来自fail回调的错误
      const errorData = res.data || {
        code: 0,
        msg: res.errMsg || "请求失败",
        error: res,
      };
      uni.showToast({
        title: errorData.msg || "请求失败",
        icon: "none",
        duration: 2000,
      });
      reject(errorData);
      return;
    }

    // 处理HTTP错误状态码
    if (res.statusCode && (res.statusCode < 200 || res.statusCode >= 300)) {
      const errorData = {
        code: res.statusCode,
        msg: "请求失败",
        error: res,
      };
      switch (res.statusCode) {
        case 404:
          errorData.msg = "请求地址错误";
          break;
        case 500:
          errorData.msg = "服务器内部错误";
          break;
        default:
          break;
      }
      uni.showToast({
        title: errorData.msg,
        icon: "none",
        duration: 2000,
      });
      reject(errorData);
      return;
    }

    // 处理响应拦截
    let responseData = res.data;
    this.interceptors.response.forEach((interceptor) => {
      responseData = interceptor(responseData, res) || responseData;
    });

    // 确保responseData存在
    if (!responseData) {
      const errorData = {
        code: 0,
        msg: "服务器返回数据格式错误",
        data: null,
      };
      uni.showToast({
        title: errorData.msg,
        icon: "none",
        duration: 2000,
      });
      reject(errorData);
      return;
    }

    // 业务逻辑处理
    const { code, msg, data } = responseData;
    if (code === 1 || code === 200) {
      resolve(data);
    } else {
      uni.showToast({
        title: msg || "请求失败",
        icon: "none",
        duration: 2000,
      });
      reject({ code, msg, data });
    }
  }

  // 发送请求
  request(options = {}) {
    const {
      url,
      method = "GET",
      data,
      header,
      loading = true,
      ...rest
    } = options;
    // 构建完整URL
    const finalUrl = url.startsWith("http")
      ? url
      : `${this.config.baseURL}${url}`;

    // 处理请求拦截
    let modifiedConfig = { url: finalUrl, method, data, header, ...rest };
    this.interceptors.request.forEach((interceptor) => {
      modifiedConfig = interceptor(modifiedConfig) || modifiedConfig;
    });

    // 显示加载
    let loadingTask = null;
    if (loading && this.config.loading) {
      loadingTask = uni.showLoading({
        title: this.config.loadingText,
        mask: true,
      });
    }

    return new Promise((resolve, reject) => {
      uni.request({
        url: modifiedConfig.url,
        method: modifiedConfig.method,
        data: modifiedConfig.data,
        header: { ...this.config.header, ...modifiedConfig.header },
        timeout: this.config.timeout,
        success: (res) => {
          // 隐藏加载
          if (loadingTask) uni.hideLoading();
          this.handleResponse(res, resolve, reject);
        },
        fail: (err) => {
          if (loadingTask) uni.hideLoading();
          this.handleResponse(err, resolve, reject);
        },
      });
    });
  }

  // 简化常用方法
  get(url, data, options = {}) {
    return this.request({ url, method: "GET", data, ...options });
  }

  post(url, data, options = {}) {
    return this.request({ url, method: "POST", data, ...options });
  }

  put(url, data, options = {}) {
    return this.request({ url, method: "PUT", data, ...options });
  }

  delete(url, data, options = {}) {
    return this.request({ url, method: "DELETE", data, ...options });
  }
}

// 创建全局实例
const http = new HttpRequest();

// // 添加全局拦截器（示例）
// http.addRequestInterceptor(config => {
//   // 添加token（从本地存储获取）
//   const token = uni.getStorageSync('token')
//   if (token && config.needAuth) {
//     config.header['Authorization'] = `Bearer ${token}`
//   }
//   return config
// })

// http.addResponseInterceptor((response) => {
//   // 统一处理token过期（示例）
//   if (response.code === 401) {
//     uni.showToast({ title: '登录过期，请重新登录', icon: 'none' })
//     uni.reLaunch({ url: '/pages/login/login' })
//   }
//   return response
// })

export default http;
